package command

import (
	"fmt"
	"os"
	"os/signal"
	"probe/internal/logger"
	"probe/internal/report"
	"syscall"

	"github.com/spf13/cobra"
)

var (
	RunCmd = &cobra.Command{
		Use:   "run",
		Short: "run",
		Long:  `run.`,
		Run: func(cmd *cobra.Command, args []string) {
			Run(args)
		},
	}

	times    int
	signals  chan os.Signal
	duration int
)

func init() {

	signals = make(chan os.Signal, 1)

	// 参数：运行次数
	RunCmd.Flags().IntVarP(&times, "times", "t", 0, "run times")
	RunCmd.Flags().IntVarP(&duration, "duration", "d", 10, "duration(minute)")
}

func Run(args []string) {

	go func() {
		startProberService(times, duration)
	}()

	// 监听信号
	// signals = make(chan os.Signal, 1)
	signal.Notify(signals, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)

	// Use a simple channel send/receive instead of select with a single case
	<-signals

	// 释放资源
	fmt.Println("[Prober] exit")
}

func FetchRPT() {
	logger.Info("fetch report")
	rpt := report.NewReport()
	if err := rpt.Fetch(); err != nil {
		logger.Errorf("fetch report error:%v", err)
		return
	}
	if err := rpt.Save(); err != nil {
		logger.Errorf("save report error:%v", err)
		return
	}
}
